Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only gossip connected peers #38

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft

Conversation

gartnera
Copy link
Member

@gartnera gartnera commented Nov 23, 2024

We should only gossip peers that are actually connectable.

Also only connect to peer if there are not any connections.

Summary by CodeRabbit

  • New Features

    • Introduced a new method to retrieve currently connected peers, enhancing the accuracy of peer discovery.
  • Improvements

    • Renamed the method for clarity, ensuring users have a better understanding of its functionality.
    • Updated the discovery process to share only actively connected peers, improving the overall reliability of peer information.

@gartnera gartnera requested review from brewmaster012 and a team November 23, 2024 00:55
Copy link

coderabbitai bot commented Nov 23, 2024

📝 Walkthrough

Walkthrough

The pull request introduces significant modifications to the PeerDiscovery struct in the p2p/discovery.go file. Key changes include renaming the GetPeers method to GetKnownPeers for clarity, and adding a new method, GetConnectedPeers, which retrieves currently connected peers. The handleDiscovery method is updated to use GetConnectedPeers, ensuring that only actively connected peers are shared. Additionally, the logic in the gossipPeers method is refined to prevent connection interruptions by checking for existing connections to peers.

Changes

File Change Summary
p2p/discovery.go - Renamed method GetPeers to GetKnownPeers.
- Added method GetConnectedPeers.
- Updated handleDiscovery to use GetConnectedPeers.
- Modified gossipPeers to replace GetPeers with GetKnownPeers and refined connection logic.

Possibly related PRs

  • fix infinite discovery address leak #37: The changes in this PR involve modifications to the PeerDiscovery struct in the same p2p/discovery.go file, specifically in the addPeer method, which is related to the overall peer management logic that is also addressed in the main PR.

Suggested reviewers

  • morde08
  • fbac

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint (1.61.0)

level=warning msg="[config_reader] The configuration option linters.errcheck.ignore is deprecated, please use linters.errcheck.exclude-functions."
level=warning msg="The linter 'deadcode' is deprecated (since v1.49.0) due to: The owner seems to have abandoned the linter. Replaced by unused."
level=warning msg="The linter 'golint' is deprecated (since v1.41.0) due to: The repository of the linter has been archived by the owner. Replaced by revive."
level=error msg="[linters_context] deadcode: This linter is fully inactivated: it will not produce any reports."
level=error msg="[linters_context] golint: This linter is fully inactivated: it will not produce any reports."


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@gartnera gartnera marked this pull request as draft November 23, 2024 00:58
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
p2p/discovery.go (1)

215-227: Enhance error handling and logging.

While the connection check is a good addition, consider these improvements:

  1. Add specific error type checks for better error handling
  2. Include more context in error logs
 if len(pd.host.Network().ConnsToPeer(p.ID)) == 0 {
     err := pd.host.Connect(ctx, p)
     if err != nil {
+        // Check for specific error types
+        if errors.Is(err, context.DeadlineExceeded) {
+            pd.logger.Warn().
+                Err(err).
+                Stringer("to", p.ID).
+                Msg("Connection attempt timed out")
+            return
+        }
         pd.logger.Error().Err(err).
             Stringer("to", p.ID).
+            Int("known_addrs", len(p.Addrs)).
             Msg("Failed to connect to peer")
         return
     }
     pd.logger.Debug().
         Stringer("to", p).
+        Int("addr_count", len(p.Addrs)).
         Msg("Connected to peer")
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8535262 and 6c949b9.

📒 Files selected for processing (1)
  • p2p/discovery.go (5 hunks)
🔇 Additional comments (3)
p2p/discovery.go (3)

Line range hint 97-108: LGTM! Improved method naming.

The renaming from GetPeers to GetKnownPeers better reflects the method's purpose and distinguishes it from the new GetConnectedPeers method.


157-159: LGTM! Improved peer sharing logic.

The change to share only connected peers aligns with the PR objective and improves the reliability of peer discovery by ensuring only connectable peers are shared.


Line range hint 1-277: Verify impact on connection handling performance.

The changes to only gossip connected peers and prevent reconnections could impact the network's ability to maintain connections under certain conditions.

✅ Verification successful

Connection handling implementation is robust and well-designed

The codebase demonstrates a solid implementation of connection handling with:

  • Appropriate timeout configurations (10s for gossip operations)
  • Proper error handling and logging for connection failures
  • Built-in concurrency control with MaxGossipConcurrency
  • Smart connection logic that prevents redundant connections
  • Graceful connection management through context cancellation

The changes to only gossip connected peers and prevent reconnections are actually beneficial:

  • Reduces network overhead by avoiding redundant connections
  • Prevents connection thrashing when addresses change
  • Maintains stable connections through proper timeout and error handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential connection handling issues in the codebase

# Look for connection timeout configurations
rg -A 2 "context.*WithTimeout|SetDeadline|SetReadDeadline|SetWriteDeadline"

# Check for connection retry logic
rg -A 5 "Connect.*retry|reconnect|backoff"

# Look for connection error handling patterns
rg -A 3 "Failed to connect|connection.*failed|connection.*error"

Length of output: 4880

Comment on lines +109 to +140
// GetConnectedPeers returns all currently connected peers
func (pd *PeerDiscovery) GetConnectedPeers() []peer.AddrInfo {
conns := pd.host.Network().Conns()
peerMap := make(map[peer.ID]peer.AddrInfo)

for _, conn := range conns {
remotePeer := conn.RemotePeer()
remoteAddr := conn.RemoteMultiaddr()

if peerInfo, exists := peerMap[remotePeer]; exists {
// peer already in map, add the new address if it's not already there
if !multiaddr.Contains(peerInfo.Addrs, remoteAddr) {
peerInfo.Addrs = append(peerInfo.Addrs, remoteAddr)
peerMap[remotePeer] = peerInfo
}
} else {
// new peer, add to map
peerMap[remotePeer] = peer.AddrInfo{
ID: remotePeer,
Addrs: []multiaddr.Multiaddr{remoteAddr},
}
}
}

// flatten map
peers := make([]peer.AddrInfo, 0, len(peerMap))
for _, peerInfo := range peerMap {
peers = append(peers, peerInfo)
}

return peers
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider adding concurrency protection and error handling.

While the implementation is functionally correct, consider these improvements:

  1. Add mutex protection as the method accesses shared network state
  2. Add error handling for edge cases (e.g., connection state changes during iteration)
 func (pd *PeerDiscovery) GetConnectedPeers() []peer.AddrInfo {
+    pd.mu.RLock()
+    defer pd.mu.RUnlock()
+
     conns := pd.host.Network().Conns()
     peerMap := make(map[peer.ID]peer.AddrInfo)
 
     for _, conn := range conns {
+        // Skip if connection is closing
+        if conn.Stat().Direction == network.DirUnknown {
+            continue
+        }
         remotePeer := conn.RemotePeer()
         remoteAddr := conn.RemoteMultiaddr()

Committable suggestion skipped: line range outside the PR's diff.

@swift1337
Copy link

As we plan to drop peer discovery via gossip, shall we close this PR?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants